package com.xianshijian.oauth.server.steps;

import java.net.URI;

import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import com.xianshijian.oauth.server.AbstractSpringCucumber;

import cucumber.api.PendingException;
import cucumber.api.java.zh_cn.假设;
import cucumber.api.java.zh_cn.当;
import cucumber.api.java.zh_cn.那么;

public class PostAuthStepdef extends AbstractSpringCucumber {
	String clientId;
	String clientdSecret;
	ResultActions ra;
	private String password;
	private String username;

	@假设("^我在第三方$")
	public void 我在第三方() throws Throwable {
		// 我在第三方站点or App里
		// 保存第三方client id
		// 保存第三方client secret
		String clientId = "1";
		String clientSecret = "1";
		this.clientId = clientId;
		this.clientdSecret = clientSecret;
		// 初始化mvc
		mvc = MockMvcBuilders.webAppContextSetup(wac).build();
		// TODO 做数据库清理工作.
		throw new PendingException();
	}

	@假设("^没有在兼客登录$")
	public void 没有在兼客登录() throws Throwable {
		// 即请求兼客的时候cookies是不存在的.

	}

	@当("^我点击使用兼客登录$")
	public void 我点击使用兼客登录() throws Throwable {
		// TODO 请求认证的接口地址

		URI authUrl = URI.create("/api/auth");
		// 发送请求到我们的AS服务端.
		ra = mvc.perform(MockMvcRequestBuilders.get(authUrl).param("redirectUrl", "http://localhost:8080/redirect")
				.param("clientId", clientId).param("scope", "http://localhost:8080/users/1"));
		// TODO login url
		throw new PendingException();
	}

	@那么("^应该让跳转到我们的登录页$")
	public void 应该让跳转到我们的登录页() throws Throwable {
		String loginUrl = "/pages/login";
		String expectedUrl = loginUrl;
		// ra.andDo(MockMvcResultHandlers.print());
		ra.andExpect(MockMvcResultMatchers.redirectedUrl(expectedUrl));
	}

	@当("^我输入账号\"([^\"]*)\"密码\"([^\"]*)\"$")
	public void 我输入账号_密码(String username, String password) throws Throwable {
		this.username = username;
		this.password = password;
	}

	@当("^点击登录$")
	public void 点击登录() throws Throwable {
		// 请求到登录页面.
		URI loginUrl = URI.create("/api/login");
		ra = mvc.perform(MockMvcRequestBuilders.post(loginUrl).param("username", username).param("password", password));
	}

	@那么("^应该让我跳转到授权页面$")
	public void 应该让我跳转到授权页面() throws Throwable {
		String authUrl = "/pages/auth";
		String expectedUrl = authUrl;
		ra.andExpect(MockMvcResultMatchers.redirectedUrl(expectedUrl));
	}

	@假设("^我在兼客登录了$")
	public void 我在兼客登录了() throws Throwable {
		// 请求到登录页面.
		URI loginUrl = URI.create("/api/login");
		ra = mvc.perform(MockMvcRequestBuilders.post(loginUrl).param("username", username).param("password", password));
	}

}
